<template>
  <div class="dept-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">班级管理</h1>
      <el-button 
        type="primary" 
        class="add-btn" 
        @click="openDialog"
      >
        <el-icon><Plus /></el-icon>
        <span>新增班级</span>
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="班级名称">
          <el-input 
            v-model="searchKeyword" 
            placeholder="请输入班级名称" 
            clearable 
            @keyup.enter="searchClazz"
            class="search-input"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="searchClazz"
            class="search-btn"
          >
            <el-icon><Search /></el-icon>
            <span>查询</span>
          </el-button>
          <el-button 
            @click="resetSearch"
            class="reset-btn"
          >
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格区域 -->
    <el-card class="data-card">
      <el-table 
        :data="pageData.list" 
        stripe 
        border 
        fit
        highlight-current-row
        class="dept-table"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="班级名称" width="150" align="center" />
        <el-table-column prop="room" label="教室" width="120" align="center" />
        <el-table-column prop="beginDate" label="开始日期" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.beginDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="masterId" label="班主任ID" width="100" align="center" />
        <el-table-column prop="subject" label="科目" width="120" align="center">
          <template #default="scope">
            {{ subjectOptions.find(opt => opt.value === scope.row.subject)?.label || scope.row.subject }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="185" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="190" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="openEditDialog(scope.row)"
              class="action-btn edit-btn"
            >
              <el-icon><Edit /></el-icon>
              <span>修改</span>
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteClazz(scope.row.id!, scope.row.name)"
              class="action-btn delete-btn"
            >
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageData.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total"
          background
        />
      </div>
    </el-card>

    <!-- 新增班级对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增班级"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><OfficeBuilding /></el-icon>
        <span>新增班级</span>
      </template>
      <el-form
        :model="clazzForm"
        :rules="rules"
        ref="clazzFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="clazzForm.name" />
        </el-form-item>
        <el-form-item label="教室" prop="room">
          <el-input v-model="clazzForm.room" />
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker
            v-model="clazzForm.beginDate"
            type="datetime"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="clazzForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="班主任ID" prop="masterId">
          <el-input v-model.number="clazzForm.masterId" type="number" />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-select v-model.number="clazzForm.subject" style="width: 100%">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="addClazz"
          class="dialog-btn confirm-btn"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改班级对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改班级"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><OfficeBuilding /></el-icon>
        <span>修改班级</span>
      </template>
      <el-form
        :model="editClazzForm"
        :rules="rules"
        ref="editClazzFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="editClazzForm.name" />
        </el-form-item>
        <el-form-item label="教室" prop="room">
          <el-input v-model="editClazzForm.room" />
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker
            v-model="editClazzForm.beginDate"
            type="datetime"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="editClazzForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="班主任ID" prop="masterId">
          <el-input v-model.number="editClazzForm.masterId" type="number" />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-select v-model.number="editClazzForm.subject" style="width: 100%">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="editClazzForm.createTime" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="updateClazz"
          class="dialog-btn confirm-btn"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { 
  ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, 
  ElMessage, ElMessageBox, ElSelect, ElOption, ElPagination 
} from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Delete, 
  OfficeBuilding, Close, Check 
} from '@element-plus/icons-vue'

interface Clazz {
  id?: number;
  name: string;
  room: string;
  beginDate: string;
  endDate: string;
  masterId: number;
  subject: number;
  createTime: string;
  updateTime: string;
}

// 分页数据
const pageData = ref({
  list: [] as Clazz[],
  total: 0,
  page: 1,
  pageSize: 5
})

// 查询关键字
const searchKeyword = ref('')

// 加载分页数据
const loadPageData = async () => {
  try {
    const params = {
      page: pageData.value.page,
      pageSize: pageData.value.pageSize
    }
    const result = await axios.get('http://localhost:8080/clazz/list', { params })
    
    // 根据您的后端返回结构调整
    pageData.value.list = result.data.data.rows || []
    pageData.value.total = result.data.data.total || 0
    
    // 添加调试日志
    console.log('分页数据:', {
      requestParams: params,
      responseData: result.data,
      pageData: pageData.value
    })
  } catch (error) {
    console.error('加载班级数据失败', error)
    ElMessage.error('加载班级数据失败')
  }
}

// 查询班级方法
const searchClazz = async () => {
  if (!searchKeyword.value.trim()) {
    pageData.value.page = 1
    await loadPageData()
    return
  }
  
  try {
    const result = await axios.get(`http://localhost:8080/clazz/${searchKeyword.value}`)
    pageData.value.list = result.data.data ? [result.data.data] : []
    pageData.value.total = pageData.value.list.length
    pageData.value.page = 1
    if (pageData.value.list.length === 0) {
      ElMessage.warning('未找到匹配的班级')
    }
  } catch (error) {
    console.error('查询班级失败', error)
    ElMessage.error('查询班级失败')
  }
}

// 重置查询
const resetSearch = async () => {
  searchKeyword.value = ''
  pageData.value.page = 1
  await loadPageData()
}

// 页码变化
const handleCurrentChange = (page: number) => {
  pageData.value.page = page
  loadPageData()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  pageData.value.pageSize = size
  pageData.value.page = 1
  loadPageData()
}

// 控制对话框显示
const dialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单数据
const clazzForm = ref<Clazz>({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: 0,
  subject: 0,
  createTime: '',
  updateTime: ''
})

const editClazzForm = ref<Clazz>({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: 0,
  subject: 0,
  createTime: '',
  updateTime: ''
})

// 科目选项
const subjectOptions = [
  { value: 1, label: '语文' },
  { value: 2, label: '数学' },
  { value: 3, label: '英语' },
  { value: 4, label: '物理' },
  { value: 5, label: '化学' }
]

// 验证规则
const rules = ref({
  name: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' },
    { max: 30, message: '班级名称不能超过30个字符', trigger: 'blur' }
  ],
  room: [
    { required: true, message: '教室不能为空', trigger: 'blur' },
    { max: 20, message: '教室名称不能超过20个字符', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '开始日期不能为空', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '结束日期不能为空', trigger: 'change' }
  ],
  masterId: [
    { required: true, message: '班主任ID不能为空', trigger: 'blur' },
    { type: 'number', message: '必须为数字值', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '科目不能为空', trigger: 'change' }
  ]
})

// 打开新增对话框
const openDialog = () => {
  const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
  clazzForm.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: 0,
    subject: 0,
    createTime: now,
    updateTime: now
  }
  dialogVisible.value = true
}

// 打开修改对话框
const openEditDialog = (clazz: Clazz) => {
  editClazzForm.value = {
    id: clazz.id,
    name: clazz.name,
    room: clazz.room,
    beginDate: clazz.beginDate,
    endDate: clazz.endDate,
    masterId: clazz.masterId,
    subject: clazz.subject,
    createTime: clazz.createTime,
    updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
  }
  editDialogVisible.value = true
}

// 新增班级
const addClazz = async () => {
  try {
    await axios.post('http://localhost:8080/clazz', clazzForm.value)
    ElMessage.success('班级添加成功')
    dialogVisible.value = false
    await loadPageData()
  } catch (error) {
    console.error('班级添加失败', error)
    ElMessage.error('班级添加失败')
  }
}

// 修改班级
const updateClazz = async () => {
  try {
    await axios.put('http://localhost:8080/clazz', editClazzForm.value)
    ElMessage.success('班级修改成功')
    editDialogVisible.value = false
    await loadPageData()
  } catch (error) {
    console.error('班级修改失败', error)
    ElMessage.error('班级修改失败')
  }
}

// 删除班级
const deleteClazz = (id: number, name: string) => {
  ElMessageBox.confirm(
    `确定要删除班级【${name}】吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      showClose: false
    }
  ).then(async () => {
    try {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      
      await axios.delete(`http://localhost:8080/clazz/${id}`)
      ElMessage.success('班级删除成功')
      await loadPageData()
      
      loading.close()
    } catch (error) {
      console.error('班级删除失败', error)
      ElMessage.error('班级删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 对话框关闭前处理
const handleDialogClose = (done: () => void) => {
  done()
}

// 初始化加载
onMounted(() => {
  loadPageData()
})
</script>

<style scoped>
/* 引入Tailwind CSS工具类 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .transition-all-300 {
    transition: all 0.3s ease;
  }
  .shadow-hover {
    transition: box-shadow 0.3s ease, transform 0.3s ease;
  }
  .shadow-hover:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
  }
}

/* 页面整体样式 */
.dept-management-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #334155;
  margin: 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 24px;
  background-color: #4f46e5;
  margin-right: 10px;
  border-radius: 2px;
}

/* 搜索卡片样式 */
.search-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  padding: 16px 20px;
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  padding-left: 10px;
  transition: all 0.2s;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #4f46e5;
}

.search-icon {
  color: #94a3b8;
}

.search-btn,
.reset-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
}

.search-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.search-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}

.reset-btn {
  margin-left: 10px;
}

.reset-btn:hover {
  color: #4f46e5;
  border-color: #4f46e5;
}

/* 新增按钮样式 */
.add-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #10b981;
  border-color: #10b981;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.add-btn:hover {
  background-color: #059669;
  border-color: #059669;
  transform: translateY(-1px);
}

.add-btn el-icon {
  margin-right: 6px;
}

/* 数据卡片样式 */
.data-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 220px); /* 根据实际布局调整高度 */
}

.data-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.dept-table {
  flex: 1;
  overflow: auto;
}

.dept-table :deep(.el-table__header) {
  background-color: #f1f5f9;
}

.dept-table :deep(.el-table__header th) {
  font-weight: 600;
  color: #334155;
}

.dept-table :deep(.el-table__row) {
  transition: all 0.2s;
}

.dept-table :deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

.dept-table :deep(.el-table__cell) {
  padding: 12px 0;
}

/* 操作按钮样式 */
.action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
  margin: 0 4px;
}

.action-btn el-icon {
  margin-right: 4px;
}

.edit-btn {
  background-color: #e0f2fe;
  border-color: #e0f2fe;
  color: #0284c7;
}

.edit-btn:hover {
  background-color: #bae6fd;
  border-color: #bae6fd;
}

.delete-btn {
  background-color: #fee2e2;
  border-color: #fee2e2;
  color: #ef4444;
}

.delete-btn:hover {
  background-color: #fecaca;
  border-color: #fecaca;
}

/* 分页样式 */
.pagination-container {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: white;
  border-top: 1px solid #e2e8f0;
}

/* 对话框样式 */
.form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.form-dialog :deep(.el-dialog__header) {
  background-color: #f8fafc;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
}

.form-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #334155;
  display: flex;
  align-items: center;
}

.form-dialog :deep(.el-dialog__title) el-icon {
  margin-right: 8px;
  color: #4f46e5;
}

.form-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #475569;
}

.dialog-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  border: 1px solid #e2e8f0;
  color: #64748b;
}

.cancel-btn:hover {
  border-color: #4f46e5;
  color: #4f46e5;
}

.confirm-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.confirm-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}
</style>